if SERVER then AddCSLuaFile( "Incomming.lua" ) end

local GM = IMiniGame.New();
GM["Info"]["Name"] = "Incomming"
GM["Info"]["Version"] = "1.0"
GM["Info"]["up_date"] = "22 November 2010"
GM["Info"]["Author"]["Name"] = "Ningaglio"
GM["Info"]["Author"]["Email"] = "Ningaglio@CitronGamers.com"
GM["Info"]["Author"]["URL"] = "http://www.citrongamers.com"
GM["Info"]["Info"] = "Bombs fall from the sky to kill you"
GM["Info"]["Description"] = "Don't let the bombs get to you!"
GM["Info"]["Icon"] = "gui/silkicons/bomb"

local Alive = player.GetAll()

function GM.Functions.RestartGame()
	IMiniGame.Unload()
	IMiniGame.Load( "Incomming" )
end

function GM.Hooks.PlayerDeath( p )
	for k,v in pairs( Alive ) do
		if v == p then Alive[ k ] = nil end
	end
	if #Alive == 0 then PrintMessage( HUD_PRINTCENTER , p:Nick() .. " Has won the game!" ) ; GM.Functions.RestartGame() end
end
 
function GM.Hooks.PlayerDeathThink( p )
	local alive = { }
	for k,v in pairs( player.GetAll() ) do
		if v:Alive() then alive[ k ] = v end
	end
	if #alive == 1 then 
		local function KillHim( pl )
			pl:Kill()
		end
		timer.Simple( 5 , KillHim , pl )
	elseif #alive == 0 then
		p:Spawn()
		return true
	else
		return false
	end
end

local bombs = { }

function GM.Hooks.Think( )
	for _,bomb in pairs( bombs ) do
		if bomb and bomb:IsValid() then
			local _ents = ents.FindInSphere( bomb:GetPos(), 35 )
			for __,pl in pairs( _ents ) do
				if pl:IsPlayer() then
					pl:Kill()
					local boom = ents.Create( "env_explosion" )
					boom:SetPos( bomb:GetPos( ) )
					boom:Spawn( )
					boom:Fire( "explode", "", 0 )
					bomb:Remove()
				end
			end
		end
	end
end


function GM.Functions.SpawnBombs()
	for k,v in pairs( player.GetAll() ) do
		local bomb = ents.Create( "prop_physics" )
		bomb:SetModel( Model( "models/Combine_Helicopter/helicopter_bomb01.mdl" ) )
		bomb:SetPos( v:GetPos() + Vector( math.random( - 50 , 50 ), math.random( - 50 , 50 ), 300 ) )
		bomb:Spawn()
		local function remove( b )
			if b:IsValid() then
				local boom = ents.Create( "env_explosion" )
				boom:SetPos( b:GetPos( ) )
				boom:Spawn( )
				boom:Fire( "explode", "", 0 )
				bomb:Remove()
				b:Remove()
			end
		end
		timer.Simple( 10 , remove , bomb )
		bombs[ #bombs + 1 ] = bomb
	end
end

function GM.Functions.OnPostLoad()
	timer.Create( "IMiniGame:Bombs" , 5 , 0 , GM.Functions.SpawnBombs )
end

function GM.Functions.OnUnload()
	timer.Remove( "IMiniGame:Bombs" )
	for k,v in pairs( bombs) do
		if v and v:IsValid() then 
			v:Remove()
		end
	end
	return true
end

function GM.Hooks.PlayerLoadout( pl ) return true end
function GM.Hooks.SpawnMenuEnabled() return false end
function GM.Hooks.SpawnMenuOpen() return false end
function GM.Hooks.ContextMenuOpen() return false end
function GM.Hooks.PopulateToolMenu() return false end
function GM.Hooks.PlayerNoClip() return false end

GM:Register()